
/* tech_news_aggregator/frontend/js/news-render.js */

/**
 * 科技新闻聚合器 - 新闻渲染模块
 * 从localStorage读取数据并负责渲染页面
 * 实现分类筛选和关键词高亮功能
 */

// 全局变量
let allNews = [];
let currentFilter = 'all'; 
let currentSearch = '';
let lastUpdated = null;

// DOM 元素引用
const elements = {
  newsContainer: document.getElementById('newsConlts'),
  lastUpdate: document.getElementById('lastUpdate'),
  searchInput: document.getElementById('searchInput')
};

/**
 * 初始化新闻渲染模块
 */
function initNewsRenderer() {
  // 绑定事件监听
  document.addEventListener('newsUpdated', renderNews);
  window.addEventListener('DOMContentLoaded', loadAndRenderNews);
  
  // 监听搜索输入框回车事件
  elements.searchInput.addEventListener('keypress', function(key === 'Enter') {
      searchNews();
    }
  });
  
  // 初始加载数据
  loadAndRenderNews();
}

/**
 * 从localStorage加载新闻数据并渲染
 */
function loadAndRenderNews() {
  const cachedNews = localStorage.getItem('cachedNews');
  const lastUpdatedTime = localStorage.getItem('lastUpdated');
  
  if (cachedNews && lastUpdatedTime) {
    try {
      allNews = JSON.parse(cachedNews);
      lastUpdat   }
  } else {
    // 无缓存数据，显示加载中
    elements.loading.classList.remove('hidden');
    elements.newsContainer.classList.add('hidden');
  }
}

/**
 * 渲染新闻列表
 */
function renderNews() {
  consteredNews = filteredNews.filter(news => news.category === currentFilter);
  }
  
  // 按关键词搜索过滤
  if (currentSearch) {
    const searchTerm = currentSearch.toLowerCase();
    filteredNews = filteredNews.filter(news => 
      news.title.toLowerCase().includes(searchTerm) || 
      (news.summary && news.summary.toLowerCase().includes(searchTerm)) ||
      (news.keywords && news.keyword : '';
      return { ...news, highlightedTitle, highlightedSummary };
    });
  }
  
  // 清空容器
  container.innerHTML = '';
  
  // 无结果处理
  if (filteredNews.length === 0) {
    noResults.class(news.publish_time)}
          </span>
        </div>
        <h3 class="text-xl font-semibold mb-2 text-gray-800 dark:text-white">
          <a href="${news.url}" target="_blank" class="hover:text-blue-500 dark:hover:text-blue-400">
            ${news.highlightedTitle || news.title}
          </a>
        </h3>
        <p class="text-gray-600 dark:text-gray-300 mb-3">
          ${-sm text-gray-500 dark:text-gray-400">
            ${news.source}
          </span>
          <button onclick="shareNews('${encodeURIComponent(news.title)}', '${encodeURIComponent(news.url)}')*/
function renderKeywords(keywords) {
  if (!keywords) return '';
  
  const keywordArray = typeof keywords === 'string' 
    ? keywords.split(',') 
    : keywords;
    
  if (!keywordArray.l-gray-300 rounded">
          ${keyword.trim()}
        </span>`
      ).join('')}
    </div>
  `;
}

/**
 * 文本关键词高亮
 * @param {string} text - 原始文本
 * @param {string} searchTerm - 搜索关键词
 * @returns {string} 高亮后的HTML
 */
function highlightText(text, searchTerm) {
  if (!searchTerm || !text) return text;
  
  // 构建正则表达式，忽略大小写
  try {
    const regex = new RegExp(`(${escapeRegExp(seararam {string} string - 需要转义的字符串
 * @returns {string} 转义后的字符串
 */
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

/**
 * 获取分类对应的颜色样式
 * @param {string工智能': 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300',
    '区块链': 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300',
    '生物科技': 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300',
    '硬件': 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300',
    '互联网': 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue{string} timeString - 时间字符串
 * @returns {string} 格式化后的时间
 */
function formatTime(timeString) {
  if (!timeString) return '';
  
  // 尝试解析时间
  const date = new Date(timeString);
  if (isNaN(dat
  // 格式化为"MM-DD HH:MM"格式
  return `${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
}

/**
 * 数值补零
 * @param {number} num - 需要补零的数字
 * @returns {string} 补零后的字符串
 */
function padZero(num) {
  return num < 10 ? `0${num}` : num;
}

/**
 * 更新最后更新时间显示
 * @param {number} timestamp - 时间戳
 */
function updateLastUpdateTime(timestamp) {
  const date = new Date(timestamp);
  const formattedDate = `${date.getFullYear()}-${padZero(date.getMonth()+1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
  elements.lastUpdate.textContent = formattedDate;
}

/**
 * 显示加载错误提示
 */
function showLoadingError() {
  elements.loading.innerHTML = `
    <p class="text-red-500">加载新tegory) {
  currentFilter = category;
  currentSearch = '';
  elements.searchInput.value = '';
  
  // 更新活动按钮状态
  document.querySelectorAll('.filter-btn').forEach(btn => {
    btn.classList.remove('active');
    if (btn.textContent.trim() === category || (category === 'all' && btn.textContent.trim() === '全部')) {
      btn.classList.add('active');
    }
  });
  
  renderNews();
}

/**
 * 搜索新闻
 */
function searchNews() {
  currentSearch = elements.searchInput.value.trim();
  renderNews();
}

/**
 * 分享新闻
 * @param {string} title - 新闻标题
 * @param {string} url - 新闻链接
 */
fun
    const shareUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(title)}&url=${encodeURIComponent(url)}`;
    window.open(shareUrl, '_blank');
  }
}

// 初始化渲染器
document.addEventListener('DOMContentLoaded', initNewsRenderer);

// 导出公共函数供外部使用
window.filterNews = filterNews;
window.searchNews = searchNews;
window.shareNews = shareNews;
